package com.yang.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DBHelp<T> {
	
	private Connection getConn() throws ClassNotFoundException, SQLException{
		Class.forName("com.mysql.jdbc.Driver");
		return DriverManager.getConnection("jdbc:mysql://192.168.56.1:3306/contect","root","root");
	}
	public boolean add(String sql,Object...obj){
		int row=0;
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			conn=getConn();
			ps=conn.prepareStatement(sql);
			for (int i = 0; i < obj.length; i++) {
				ps.setObject(i+1, obj[i]);
			}
			row=ps.executeUpdate();
			System.out.println(ps.toString());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		close(null,ps,conn);
		return row>0;
	} 

	public T findObj(String sql,MapRow<T> mr,Object...obj){
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		T t=null;
		try {
			conn=getConn();
			ps=conn.prepareStatement(sql);
			for (int i = 0; i < obj.length; i++) {
				ps.setObject(i+1, obj[i]);
			}
			rs=ps.executeQuery();
			System.out.println(ps.toString());
			if(rs.next()){
				t=mr.RowMap(rs);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		close(rs,ps,conn);
		return t;
	}
	public List<T> findList(String sql,MapRow<T> mr,Object...obj){
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		T t=null;
		List<T> list=new ArrayList<T>();
		try {
			conn=getConn();
			ps=conn.prepareStatement(sql);
			for (int i = 0; i < obj.length; i++) {
				ps.setObject(i+1, obj[i]);
			}
			rs=ps.executeQuery();
			while(rs.next()){
				t=mr.RowMap(rs);
				list.add(t);
			}
			System.out.println(ps.toString());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		close(rs,ps,conn);
		return list;
	}
	private void close(ResultSet rs, PreparedStatement ps, Connection conn) {
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				if(ps!=null){
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}finally{
						if(conn!=null){
							try {
								conn.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}
}
